package cn.itsource.ymcc.mq;

import cn.itsource.ymcc.constants.BaseConstants;
import cn.itsource.ymcc.domain.MessageSms;
import cn.itsource.ymcc.dto.SMSSend2MQ;
import cn.itsource.ymcc.exception.GlobleException;
import cn.itsource.ymcc.service.IMessageSmsService;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.util.Date;

@Component
@RocketMQMessageListener(consumerGroup = "service-common-smsmessage-consumer",
        topic = BaseConstants.MessageMQ.TOPIC_MESSAGE,
        selectorExpression = BaseConstants.MessageMQ.TAGS_SMS_NAME
)
@Slf4j
public class SMSMessageMQConsumer implements RocketMQListener<MessageExt> {

    @Autowired
    private IMessageSmsService messageSmsService;

    @Override
    public void onMessage(MessageExt message) {

        try {
            String bodyStr = new String(message.getBody(),"utf-8");
            SMSSend2MQ smsSend2MQ = JSON.parseObject(bodyStr, SMSSend2MQ.class);
            //用户群发
            if(smsSend2MQ.getUserIds() != null && !smsSend2MQ.getUserIds().isEmpty()){
                smsSend2MQ.getUserIds().forEach(userId->{
                    saveMessage2db(smsSend2MQ,userId);
                    log.info("短信发送：{}，{}",userId,smsSend2MQ.getContent());
                });
            }else{
                saveMessage2db(smsSend2MQ,null);
                log.info("短信发送：{}，{}",null,smsSend2MQ.getContent());
            }


        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            //通过异常来决定ACK
            throw new GlobleException("短信发送失败");
        }
    }
    public void saveMessage2db(SMSSend2MQ smsSendVO,Long userId){
        MessageSms messageSms = new MessageSms();
        messageSms.setContent(smsSendVO.getContent());
        messageSms.setSendTime(new Date());
        messageSms.setTitle(smsSendVO.getTitle());
        messageSms.setUserId(userId);
        messageSmsService.insert(messageSms);
    }
}
